<script setup>
	import {reactive, toRefs, ref} from 'vue'
    import roleApi from '@/api/sys/role'
    import userApi from '@/api/sys/user'

    //获取父组件的属性
    const props = defineProps({
        roleDrawer: Boolean
    })
    const {roleDrawer} = toRefs(props)

    //调用父组件的closeHandler方法
    const emits = defineEmits(['closeHandler'])
    //hasChange为true，需要更新列表
    const closeDrawer = (hasChange) => {
        emits('closeHandler',hasChange)
    }

    const treeData = ref([])
    const treeRef = ref(null)
    let userId = null
    //将子组件的init方法暴露给父组件
    const init = (id) => {
        userId = id
        //获取菜单列表
        roleApi.getRolePage().then(response => {
            treeData.value = response.data.records
        })

        //回显已经勾选的菜单id
        userApi.getUserDetailsById(id).then(response => {
            const roleIds = response.data.roles.map(item => item.id)
            treeRef.value.setCheckedKeys(roleIds)
        })
    }
    defineExpose({init})

    //提交表单
    import { ElMessage } from 'element-plus'
    const submitForm = () => {
        const roleIds = treeRef.value.getCheckedKeys()
        userApi.assignRolesToUser(userId,roleIds).then(response => {
            ElMessage({type: 'success',message: '操作成功',})
            closeDrawer(true)
        })
    }

</script>

<template>
	<!--新增对话框-->
	<el-drawer
			title="分配角色"
			width="600px"
            v-model="roleDrawer"
			:before-close="closeDrawer"
	>

		<el-form>
			<el-form-item>
				<el-tree
						:data="treeData"
						show-checkbox
						ref="treeRef"
						:check-strictly=true
						node-key="id"
						:default-expand-all=true
						:props="{children: 'children',label: 'name'}">
				</el-tree>
			</el-form-item>

			<el-form-item>
				<el-button type="primary" @click="submitForm()">确 定</el-button>
				<el-button @click="closeDrawer">关 闭</el-button>
			</el-form-item>
		</el-form>

	</el-drawer>
</template>

